package com.demo.forum.interceptor;

import com.demo.forum.config.AppConfig;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author 比特就业课
 * @Date 2023-05-23
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取用户session, 并判断用户是否登录
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            // 用户已登录
            return true;
        }
        // 没有登录强制跳转到登录页面
        response.sendRedirect("/sign-in.html");
        return false;
    }
}
